import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { getUserInfo } from '~/utils/crypto'
import { getBlogListXhr } from '~/api/index'
import { DEFAULT_AVATAR } from '~/const/index'
import { BLOG_TYPE_MAP } from '~/const/index'
import dayjs from 'dayjs'

const PAGE_SIZE = 12

const ArticlesPage: React.FC = () => {
  const navigate = useNavigate()
  const userInfo = getUserInfo() || {}
  const [articles, setArticles] = useState<any[]>([])
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    setLoading(true)
    getBlogListXhr({ page, pageSize: PAGE_SIZE }).then((res: any) => {
      setArticles(res?.data?.list || [])
      setTotal(res?.data?.total || 0)
      setLoading(false)
    })
  }, [page])

  const totalPages = Math.ceil(total / PAGE_SIZE)

  return (
    <div className="container  px-6 py-6">
      <h1 className="text-3xl font-bold mb-8">文章列表</h1>
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 gap-8">
        {loading ? (
          <div className="col-span-5 text-center text-gray-500">加载中...</div>
        ) : articles.length === 0 ? (
          <div className="col-span-5 text-center text-gray-400">暂无文章</div>
        ) : (
          articles.map((item) => (
            <div
              key={item.id}
              className="glass-card p-6 hover-scale"
              style={{ minHeight: 130 }}
              onClick={() => navigate(`/article/${item.id}`)}
            >
              <div className="flex items-center justify-between mb-4">
                <span className="text-blue-400">
                  #
                  {item?.category
                    ? BLOG_TYPE_MAP?.[item?.category] || '技术'
                    : '技术'}
                </span>
                <span className="text-xs text-gray-400 ml-2">
                  <i className="ri-eye-line mr-1"></i> 阅读 {item.views || 0}
                </span>
              </div>
              <h2 className="text-2xl font-bold mb-4 truncate">{item.title}</h2>
              {item.content && item.content.replace(/<[^>]+>/g, '').trim() ? (
                <p className="text-gray-500 dark:text-gray-300 mb-4 line-clamp-2">
                  {item.content.replace(/<[^>]+>/g, '').slice(0, 120)}...
                </p>
              ) : (
                <div className="h-[18px] mb-4"></div>
              )}
              <div className="flex items-center justify-between text-sm text-gray-400">
                <div className="flex items-center">
                  <i className="ri-time-line mr-2"></i>
                  <span>
                    {item?.createdAt
                      ? dayjs(item.createdAt).format('YYYY-MM-DD')
                      : ''}
                  </span>
                </div>
                <div className="flex items-center ml-4">
                  <img
                    src={item?.authorAvatar || DEFAULT_AVATAR}
                    alt="avatar"
                    className="w-6 h-6 rounded-full mr-2"
                  />
                  <span className="text-gray-600">
                    {item?.authorName || '不知名网友'}
                  </span>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {articles.length !== 0 && page !== 1 && (
        <div className="flex justify-center mt-10">
          <nav className="inline-flex rounded-md shadow-sm">
            <button
              className="px-3 py-1 border border-gray-300 rounded-l-md bg-white hover:bg-gray-100 disabled:opacity-50"
              onClick={() => setPage(page - 1)}
              disabled={page === 1}
            >
              上一页
            </button>

            <div className="px-4 py-1 border-t border-b border-gray-300 bg-white text-gray-600">
              <span className="text-blue-600">{page}</span>/{totalPages}
            </div>
            <button
              className="px-3 py-1 border border-gray-300 rounded-r-md bg-white hover:bg-gray-100 disabled:opacity-50"
              onClick={() => setPage(page + 1)}
              disabled={page === totalPages}
            >
              下一页
            </button>
          </nav>
        </div>
      )}

      {!!userInfo?.roleLevel && (
        <button
          className="fixed bottom-12 right-20 bg-blue-500 text-white p-2 rounded-full shadow-lg flex items-center justify-center"
          onClick={() => navigate('/publish')}
        >
          <span className="text-xl mr-2">+</span> 发布博客
        </button>
      )}
    </div>
  )
}

export default ArticlesPage
